/**
 *  form edit
 * 
 * 制作:  叶风
 * Qq:    355007778
 * Email: ye.fn@163.com 
 *  
 */

/**
 * Table_Ad
 *  
 */
var Table_Ad = function(){};
Table_Ad.prototype = {
    ta: null,
    // 设置选项
    set: function(opt){
        var i;
        for(i in opt)
            this[i] = opt[i];
        return this;
    },
    // colWidth
    setColumnWidth: function(){
        var o = this.ta.find('.da-kuan-h'), LS_key='appCol-' + (this.ta.attr('id')||'');
        if (o.length<1) return this;
        o.each(function(index, el) {
            var th = $(el).parents('.col-head'), f=th.attr('data-column'),w = localStorage.getItem(LS_key + f);
            if(w){th.width(parseInt(w));}
        });
        o.height(this.ta.height());
		
        var h,c,d,x,y,w, T = this;;
        o.mousedown(function(e){
            e.stopPropagation();
            h=$(this),c=h.parent(),x=e.screenX,y=e.screenY,w=c.width();
            h.addClass('da-kuan-h-act');
            d=$(document).bind('mousemove',move).bind('mouseup', up);
        });
        function move(e){
            window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();	
            var wv=w+ e.screenX - x;
            if(wv<10)return;
            c.width(wv);
            //兼容 table set over
            if(wv>c.width()){T.ta.width(function(i,n){return n+(wv-c.width());});}					
        }
        function up(){
            d.unbind('mousemove',move).unbind('mouseup', up);
            h.removeClass('da-kuan-h-act');
            if(T.ta.height()!=o.height()){o.height(T.ta.height());}
            localStorage.setItem(LS_key + h.parents('.col-head').attr('data-column'), c.width());
        }
        return this;
    },
    // move col
    u_saveDisplayCol: null,
    moveColumn: function(){
        var oo=this,mv=oo.ta.find('.mv-col'),st;
        if (mv.length<1) return this;
        
        mv.draggable({helper:'clone',axis:'x',addClasses:false,handle:'',distance:5,
                        start:function(e,ui){ui.helper.addClass('inser-td');}
                    });
        mv.droppable({greedy:false,hoverClass:'droppable-hover',addClasses:false,tolerance:'pointer',drop:_drop});
		
        function _drop(e,ui){
            var i = ui.draggable.index(),to=$(this).index();
            oo.ta.find('.sl-i').each(function(){
                var al = $(this).children();
                al.eq(i).insertAfter(al.eq(to))
            });
            ui.draggable.insertAfter(this);

            if(st)
                clearTimeout(st);		
            st = setTimeout(sc, 3000);	
        }
        function sc(){
            if(oo.u_saveDisplayCol==null)return;
            var d='';
            oo.ta.find('.col-head').each(function(){d+=','+$(this).attr('data-column');});
            $.get(oo.u_saveDisplayCol + d.substr(1), checAjaxRe);
        } 
        return this;
    },
    // 显示自定义列
    showCol_H: function(id){
        var h = $(id),o=h.next(),f=o.find('form');
        h.mouseover(function(){o.show()});
        h.click(function(){o.hide();});
        o.click(function(e){e.stopPropagation();});
        o.find('.icon-16-apply').click(function(){f.submit()});
        o.find('.icon-16-close').click(function(){f[0].reset();o.hide();});
        o.find('.icon-16-select').click(function(){f.find(':checkbox').attr('checked', !f.find(':checkbox')[0].checked);});
    },
    
    /**
     * 选择
     * @param {type} selF  选择后触发
     * @param {type} unselF
     * @returns {Table_Ad.prototype}
     */
    creSelect: function(selF,unselF){
		$('.sl-h',  this.ta).live('click',function(e){
			var a = $(this).parents('.sl-i');
			if (a.hasClass('ui-selected')){
                a.removeClass('ui-selected');
                if(unselF)unselF(e, a);
            }
			else{
                a.addClass('ui-selected');
                if(selF)selF(e, a);
            }
		});
        var t = this;
		this.ta.find('.sl-ah').click(function(){
            t.ta.find('.sl-i').toggleClass('ui-selected');
        }).dblclick(function(){
            t.ta.find('.sl-i').addClass('ui-selected')
        });
        var op ={delay:30, distance:0, filter:'.sl-i', cancel: '.nos, a', stop:selF,unselected:unselF};
        this.ta.selectable(op);
	return this;
	},
    singleSelect: function(selF){
        var o=this;
        $('.sl-h',  this.ta).live('click',function(e){
			o.ta.find('.ui-selected').removeClass('ui-selected');
            var a = $(this).parents('.sl-i').addClass('ui-selected');
            if (selF)selF(e, a);
		});
    },
    getRowID: function(o){
		var h = $(o);
		if (h.hasClass('sl-i'))
			return h.attr('i_ID');
		return h.parents('.sl-i').attr('i_ID');
	},
    getSelect_ids: function(){
		var ids = '';
		this.ta.find('.ui-selected:visible').each(function(){ids += ',' + $(this).attr('i_ID');});
		if (!ids) box(language._('qing xian xuan ze'));
		return ids.substr(1);
	},
    
    // view
    u_view: null,
	viewRow: function(){
		var e = window.event || arguments.callee.caller.arguments[0];
		var o= e.target || e.srcElement;
		w_open(this.u_view +this.getRowID(o))
        e.stopPropagation();
	},
    
    // del
    u_del: null,
	delSelect_ids: function(){
		var ids = this.getSelect_ids();
	  	if (!ids || !confirm(language._('shan chu?'))) return ;
	  	var a = this.ta.find('.ui-selected:visible').fadeTo(0,0.2);
		$.get(this.u_del + ids, function(r){if(checAjaxRe(r))a.remove();else{a.fadeTo(0,1);}});
	},
	delRow: function(){
        var e = window.event || arguments.callee.caller.arguments[0] ,o=e.target;
        e.stopPropagation();
		if (confirm(language._('shan chu?'))){
			var a = $(o).parents('.sl-i').fadeTo(0,0.2);
			$.get( this.u_del + this.getRowID(o), '', function(r){if(checAjaxRe(r))a.remove();else{a.fadeTo(0,1);}});
			return true;
		}
	},
    
    /**
     * 通过URL加载编辑
     * @param {string} url
     */
    loadEM: function(url){
        if (this.ta.hasClass('loadedEM')){
			toolbar('refresh');
            return; 
        } 
        var t=this;
		$.get(url, function(r){
            var e_att = $(r).insertAfter(t.ta),colh = [];
            t.initEdit(e_att);
            t.ta.find('.col-head').each(function(){
                var o=$(this), i=o.index(), id=o.attr('data-column'), o = e_att.filter('.data-column-'+id);
                if(o.length)
                    colh[i]= o;
            });
            t.startCE(colh);
            t.ta.addClass('loadedEM').hide('fold',{},100).show('fold',{},300);
		});
    },
	// 创建编辑器
    creEdit: function(arr){
        var f,a, str, re=[];
        for (f in arr){
            a = arr[f];
            if (a=='input'){
                str ='<div class="cell-input" data-field="'+ f +'" data-input="text"><input type="text"  /></div>';
            }else if(a=='text'){
                str ='<div class="cell-input" data-field="'+ f +'" data-input="text"><textarea></textarea></div>';
            }
            var o= $(str).appendTo('body');
            this.initEdit(o);
            re[f] = o.hide(); 
        }
        return re;
    },
    initEdit: function(a){
        var t=this;
        a.each(function(){
            var input=$(this),
                inputType =  input.attr('data-input');
            if (inputType=='text'){
                input.find(':input')
					.bind('keydown',function(e){
						if (e.keyCode == 27){ //esc
							this.blur();
						}else if (e.keyCode == 13){ //enter
							if (e.target.nodeName=='INPUT' || e.ctrlKey){
								var o = this;
								t.saveCell(this.value, input.attr('data-field'), function(){
																						t.e_item.text(o.value);
																						o.value='';
																				  });
								this.blur();
							}
						}
					 })
					.bind('blur',function(){
						input.hide();
						if(t.e_item.text()==this.value)
							this.value='';
					 });
            }else if (inputType=='select'){
                var ip = input.find('select');
                ip.bind('keydown',function(e){
                    if (e.keyCode == 27){ //esc
                        input.hide();
                    }else if (e.keyCode == 13){ //enter
                        t.saveCell(this.value, input.attr('data-field'), function(){
                            t.e_item.text($(ip).find('option:selected').text()+'');
                        });
                        input.hide();
                    }
                 })
				.bind('blur',function(){
					 input.hide();
				});
            }
        });
    },
    
	// 整列编辑
    startCE:function(colh){
		var t=this;
		t.ta.find('.sl-i').each( function(){
			var ce=$(this).children(),i;
			for(i in colh){
				ce.eq(i).find('span:first').addClass('edit').bind('click',{i:i},function(e){
					var i=e.data.i;
					t.editCell(colh[i], this);
					e.stopPropagation();
				});       
			}
		});
	},
    e_item : null,
    editCell: function(attr, o){
			this.e_item = $(o);
			var input=$(attr), t=this,
                inputType =  input.attr('data-input');
            if (inputType=='switch'){
                var sta = input.children('.switch-on').html()==t.e_item.html();
                t.saveCell(sta?0:1, input.attr('data-field'), function(){
                   t.e_item.html(input.children(sta?'.switch-off' :'.switch-on').html()+''); 
                });
            }else{
                input.show()
					 .offset(t.e_item.offset())
					 .width(Math.max(20, t.e_item.width()))
					 .height(Math.max(20, t.e_item.height()));
                var ino = input.find(':input').focus()[0];
				if (inputType=='text'){
					if (ino.value==''){
						ino.value = t.e_item.text();
					}
				}
            }
	},
    u_saveCell: '',
	saveCell: function(val, field, callFun){
		var id = this.e_item.parents('.sl-i').attr('i_ID'), a=setLoading(this.e_item[0]), t=this;
		$.post(this.u_saveCell,  'id='+ id +'&field='+ field + '&value=' + encodeURIComponent(val), function(r){
			a.restore();
			if (checAjaxRe(r)){
				if(callFun)callFun(val);
				else{t.e_item.text(val);}
			}	
		});	
	},
	add: function(){},
    save:function(){}
};
Table_Ad.init = function(t,opt){
    var T = new Table_Ad();
    if  (opt)
        T.set(opt);
    T.ta = $(t);
    T.setColumnWidth();
    T.moveColumn();
    if (T.col_h)
        T.showCol_H(T.col_h);
    if (T.u_view)
        T.ta.find('.sl-i').live('dblclick', function(){T.viewRow()});
    return T;
}


/**
 * 
 * @param {type} f 表单
 * @param {type} b 0判断选有时返true 1全选 2反选 3取消
 * @returns {Boolean}
 */ 
function xuan_ze(f, b){
	for (var i=0;i<document.forms[f].elements.length;i++){
		var e = document.forms[f].elements[i];
		if (e.type !='checkbox')
			continue;
		if (b==1)
			e.checked = true;
		else if (b==2)
			e.checked == true ? e.checked = false : e.checked = true;
		else if (b==3)
			e.checked = false;
		else if (!b && e.checked == true)
			return true;
	}
}
function xuan_zhi(f){
	var v ='';
	for (var i=0;i<document.forms[f].elements.length;i++){
		var e = document.forms[f].elements[i];
		if(e.name =='check[]' && e.checked == true)
			v += ','+ e.value;
	}
	if(v)
		return v.substr(1);
	alert(language._('qing xian xuan ze'));
}

/**
 * 提交表单保存数据
 * @param {type} f
 * @param {type} c_U
 * @param {type} act
 * @returns {undefined}
 */
function post_save(f, c_U, act, fun){
  f = $(f);
  if (!CheckForm(f[0]))
  	return;
  var bx = box(language._('bao cun zhong')),data = f.serialize(); 
  $.post( c_U +'-fsave', data, function(res){
	if (!checAjaxRe(res))
		return bx.close();	
    if (res.msg){
        bx.set(res.msg);
    }else{
        bx.set('操作成功').close(0.4);
		if (fun)fun(act, res, data);
        if (act=='save_new'){
            $('#data_id').val() ? document.location.href = c_U+'-fpost' : f[0].reset();
        }else{
            $('#data_id').val(res.id);
            if (act=='checkin')
				window.opener ?window.close() :document.location.href = c_U;
        }
		
    }	
  });
}


/**
 * 检查表单
 * check="^\S{4,}$"  4个字符
 * ^(\d{2,4}-\d{7,}(-\d+)?)?$  固话
 * 
 */ 
(function(){
var CheckForm = function(form){
    var els = $_obj(form).elements, i;
    for(i=0;i<els.length;i++){
        if (els[i].getAttribute('check')){
            var el =els[i], sReg =el.getAttribute('check'), sVal =CheckForm.getValue(el), reg = new RegExp(sReg,"i");
            if (!reg.test(sVal)){
				CheckForm.aler(el); 
                return false;
            }
        }
    }
	return true;
}
/**
 * 通用取值函数分三类进行取值
 * @param {type} el
 * @returns {String}
 */
CheckForm.getValue = function (el){
    switch(el.type){
        case "text":
        case "hidden":
        case "password":
        case "file":
        case "textarea": 
            return el.value;
        case "checkbox":
        case "radio": 
            return CheckForm.getValueChoose(el);
        case "select-one":
        case "select-multiple": 
            return CheckForm.getValueSel(el);
        default: 
            return el.value;
    }
}
/**
 * 取得radio,checkbox的选中数,用"0"来表示选中的个数,通过正则0{1,}来表示选中个数
 * @param {type} el
 * @returns {String}
 */
CheckForm.getValueChoose = function (el){
    var sValue="", i=0, tmpels = document.getElementsByName(el.name);
    for(;i<tmpels.length;i++){
        if(tmpels[i].checked)
            sValue += "0";
    }
    return sValue;
}
/**
 * 取得select的选中数,用"0"来表示选中的个数,通过正则0{1,}来表示选中个数
 * @param {type} el
 * @returns {String}
 */
CheckForm.getValueSel = function(el)
{
    var sValue = "", i=0;
    for(;i<el.options.length;i++){
        if(el.options[i].selected && el.options[i].value!="")
            sValue += "0";
    }
    return sValue;
}
CheckForm.aler =function (el){
	if (el.title){
		var _en = $(el).next('.err-note');
		_en.length ? _en.text(el.title) : alert(el.title);
	}
	$(el).hide(0).toggle("pulsate");
	switch(el.type){
		case "text":
		case "search":
		case "hidden":
		case "password":
		case "file":
		case "textarea":
			try{
				el.focus();
				var rng = el.createTextRange();
				rng.collapse(false);
				rng.select();
			}catch(e){};
			break;
		case "checkbox":
		case "radio":
			var _els = document.getElementsByName(el.name);
			_els[0].focus();
			break;
		case "select-one":
		case "select-multiple":
			el.focus();
			break;
	} 
}
window.CheckForm = CheckForm;
})();

// 生成随机码
function crePassword(o, leng)
{
	o.value = "";
	if (!leng)leng=8;
	for (var i = 0; i <leng; i++)o.value += "abcdefghijkmnpqrstuvwxyABCDEFGHJKLMNPQRSTUVWXY@-0123456789". charAt(Math.floor(Math.random() * 56));
}
function creNum(leng)
{
	return Math.floor(Math.random() * Math.pow(10, leng||4));
}

//
function openFileWin(p,way)
{
    w_open('?u=cfile\\a&select='+ (way||'') +'&'+p, 'fileBrowse', '', 'width=800,height=500,toolbar=0,scrollbars=1,resizable=yes');
}


// update_field
function post_updatedField(f){
  $(f + ' .update').each(function(){
      var a=$(this), n=a.attr('name');
      if (n)
        a.attr('_name', n).attr('name', '');
  })
  .one('focus', function(){var a=$(this);a.attr('name', a.attr('_name'));});
}

// 地区选择
function select_area(obj){
	var o = $(obj),s=SearchWordAC(o, ROOT_URL +'?u=carea\\g-fsearchWord&w=');
	s.setLiFun = function(li, d){
		$(li).text( d.name +'(' + d.py +')' );
	}
	s.selectFun = function(li, d){
		var n = d.pName + d.name;
		this.input.focus().val(n);	
		this.get( n +' ');
	}
	return s;
}